package com.szrt.service.impl;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.szrt.dao.PageDao;
import com.szrt.dao.UserDao;
import com.szrt.dao.impl.UserDaoImpl;
import com.szrt.dto.PageDTO;
import com.szrt.entity.UserEntity;
import com.szrt.service.UserService;

public class UserServiceImpl  implements UserService{

	private UserDao dao=new UserDaoImpl();
	
	//获得session工厂
	private SqlSessionFactory sessionFactory=null;
		
	
		{
			Reader reader;
			try {
				//1 加载 mybatis 的配置文件（它也加载关联的映射文件）
				String resource = "mybatisConfig.xml";
				reader = Resources.getResourceAsReader(resource);
				//2 构建 sqlSession 的工厂
				 sessionFactory = new SqlSessionFactoryBuilder().build(reader);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
	
	@Override
	public Map<String, Object> findWitdPage(PageDTO page) {
		
		Map<String, Object> map=new HashMap<String, Object>();
		//业务逻辑层做业务逻辑的简单判断
		try {
			//业务成功时的业务逻辑
			List<UserEntity> fingWithPage = dao.fingWithPage(page);
			
			//1使用mabatis获得链接，获得
			SqlSession session = sessionFactory.openSession(true);
			PageDao dao = session.getMapper(PageDao.class);
			//2获得查询的条数
			int acount = dao.queryPageAcount();
			
			//获得分页的总数目
			int pageSide = page.getPageSide();
			//如果不能整除，页数加一，否则等于页数除以分页的数
			int yeshu=acount % pageSide==0?acount/pageSide:acount/pageSide+1;
//			System.out.println(yeshu);
			
			
			map.put("messge", "操作成功");
			map.put("fingWithPage", fingWithPage);
			map.put("yeshu", yeshu);
			
			//获得当前的页数
			map.put("page",page);
			
		} catch (Exception e) {
			
			//业务失败时的操作
			map.put("messge", "操作失败");
			//获得当前的页数
			map.put("page",page);
			
			e.printStackTrace();
		}
		
		return map;
	}


	public Map<String, Object> del(String[] delId)  {
		
		Map<String, Object> map=new HashMap<String, Object>();
		//1使用mabatis获得链接，获得
		SqlSession session = sessionFactory.openSession(true);
		UserDao dao = session.getMapper(UserDao.class);
		
		int counter=0;
		for(int i=0;i<delId.length;i++){
			int did = Integer.parseInt(delId[i]);
			
			
			try {
				int id = dao.deleteById(did);
				if(id>=1){
					//删除成功返回
					map.put("code","200");
					//成功删除的条数
					counter++;
					map.put("mycounter",counter);
					
				}else{
					
					//删除失败返回
					map.put("code",333);
				}
			} catch (Exception e) {
				map.put("code",333);
				e.printStackTrace();
			}
			
		}
		
		return map;
	}

}
